package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 发送手机验证码
     * @date 2023/2/9 17:25
     * @param session
     * @param user
     * @return R<String>
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(HttpSession session, @RequestBody User user){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送短信
            log.info("手机上的验证码为{}", code);
            //保存验证码
            session.setAttribute(phone, code);
            return R.success("手机发送验证码成功");
        }
        return R.error("手机发送验证码失败");
    }

    /**
     * 移动端用户登录
     * @date 2023/2/9 17:46
     * @param session
     * @param map
     * @return R<String>
     */
    @PostMapping("/login")
    public R<User> login(HttpSession session, @RequestBody Map map){

        //生成的验证码
        String code = session.getAttribute(map.get("phone").toString()).toString();
        //手机上的验证码
        String phoneCode = map.get("code").toString();
        log.info("手机上的验证码为：{}", phoneCode);
        //验证码比对（session中的和页面提交的验证码）
        if(code != null && code.equals(phoneCode)){
            session.setAttribute("user", map.get("phone").toString());
            //判断当前用户是否为新用户
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone, map.get("phone").toString());
            User user = userService.getOne(queryWrapper);
            if(user == null){
                user = new User();
                user.setPhone(map.get("phone").toString());
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user", user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }
}
